package dnl.utils.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class MailSender {

	private static Logger logger = LoggerFactory.getLogger(MailSender.class);

	public void sendEmail(final MailAccount mailAccount, MessageDetails messageDetails) {
		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", mailAccount.getHostName());
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.auth", "true");

		if (mailAccount.getSmtpPort() != null) {
			props.put("mail.smtp.port", mailAccount.getSmtpPort());
			props.put("mail.smtp.socketFactory.port", mailAccount.getSmtpPort());
		}

		if (EncryptionType.SSL.equals(mailAccount.getEncriptionType())) {
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", "false");
			props.put("mail.smtp.starttls.enable", "true");
		}

		Authenticator auth = new javax.mail.Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				String username = mailAccount.getUser();
				String password = mailAccount.getPassword();
				return new PasswordAuthentication(username, password);
			}
		};
		Session mailSession = Session.getInstance(props, auth);
		// uncomment for debugging infos to stdout
		// mailSession.setDebug(true);
		try {
			Transport transport = mailSession.getTransport();

			MimeMessage message = new MimeMessage(mailSession);

			message.setContent(messageDetails.getContent(), "text/"
					+ messageDetails.getMimeType().toString());
			message.setSubject(messageDetails.getSubject());
			message.setFrom(new InternetAddress(mailAccount.getSendAddress()));
			String[] recipients = messageDetails.getRecipients();
			for (String recipient : recipients) {
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
			}

			transport.connect();
			transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
			transport.close();
		} catch (Exception e) {
			logger.error("", e);
		}
	}

}
